import pandas as pd

def load_mapping(file_path, key_column, value_column):
    # 读取映射Excel文件
    data = pd.read_excel(file_path)
    # 确保列名正确
    if key_column not in data.columns or value_column not in data.columns:
        raise ValueError("指定的列名在Excel文件中不存在")
    # 创建映射字典
    mapping_dict = dict(zip(data[key_column], data[value_column]))
    return mapping_dict

def apply_mapping(target_file_path, target_column, mapping_dict, output_file_path):
    # 读取目标Excel文件
    target_data = pd.read_excel(target_file_path)
    # 确保目标列名正确
    if target_column not in target_data.columns:
        pass

        #raise ValueError("指定的目标列名在Excel文件中不存在")
    # 应用映射
    target_data[target_column] = target_data[target_column].map(mapping_dict).fillna(target_data[target_column])
    # 保存结果
    target_data.to_excel(output_file_path, index=False)

def main():
    mapping_file = 'C:\\Users\\Aerle\\Desktop\\Map.xlsx'
    target_file = 'C:\\Users\\Aerle\\Desktop\\target.xlsx'
    key_column = 'Key'
    value_column = 'Value'
    # target_column = 'ColumnToReplace'
    target_column = '工厂名称'
    output_file = 'C:\\Users\\Aerle\\Desktop\\缩写后的工厂名字.xlsx'

    # 载入映射
    mapping_dict = load_mapping(mapping_file, key_column, value_column)
    # 应用映射到目标文件
    apply_mapping(target_file, target_column, mapping_dict, output_file)
    print("处理完成，更新后的文件已保存为:", output_file)

if __name__ == "__main__":
    main()
